/**
 * TODO:
 * :HOVER kaob raise nupult ära, kui disabled: true panna ning seejärel taastada
 * sidepot?
 * UTF8 .js failidele
 * showdownis mängija saab RAISEdes omale raha juurde "teha"
 */

$(document).ready(function(){
	// mängija kaartide animeerimine, kui mängija alale liikuda
	$(".pos").hover(
	
	function() {
		if (this.id[1]-1 == humanPos) {
			$("#" + this.id + "card1").animate({
				top: -72, left: 10
			}, 100);
			$("#" + this.id + "card2").animate({
				top: -72, left: 58
			}, 100);
		}
		},
	function(){
		if (this.id[1]-1 == humanPos) {
			$("#" + this.id + "card1").animate({
				top: -38, left: 25
			}, "fast");
			$("#" + this.id + "card2").animate({
				top: -38, left: 45
			}, "fast");
		}
	});
	//lisame selle "lendava kaardi", mis on visible ainult animeerimisel
	$('.table').append("<img src='./img/card_animation.gif' id = 'cardanimation' style='visibility:hidden'/>");
	
	$("#foldbutton").mousedown(function(){
		sendAction("fold");
		showPlayerButtons(false);
	});
	
	$("#checkbutton").mousedown(function(){
		sendAction("check");
		showPlayerButtons(false);
	});
	
	$("#raisebutton").mousedown(function(){
		sendAction("raise");
		showPlayerButtons(false);
	});
	

	$("#startleavebutton").mousedown(function(){
		startLeave();
		
	});
	
	$("#sendbutton").mousedown(function(){
		getTextFromTextinput();
	});
	
	$("#textinput").keypress(function (event) {
	    if (event.which == 13){
	    	getTextFromTextinput();
	    }
	});
	 showPlayerButtons(false);
});

const FOLD = 0;
const CHECK = 1;
const CALL = 2;
const RAISE = 3;
const ALLIN = 4;
const WINNER = 6;
const SHOWDOWLENGTH = 5000;

function showPlayerButtons(boolean){
	if (boolean){ // kui kord inimese käes, siis näitame talle nuppe
		$(".button").fadeIn();
	}
	else {
		$(".button").fadeOut("fast");
	}
}
var prevId = null;
function updateActivePlayer(playerId){
	var humanActive = false;
	for (var i=0; i < players.length; i++){
		if (players[i].id == playerId && players[i].isHuman){
			showPlayerButtons(true);
			humanActive = true;
		}
	}
	
	if (!humanActive){
		showPlayerButtons(false);
	}
	var prevColor = null;
	// värvime aktiivse mängija nime valgeks ja eelneva mängija nime tagasi halliks
	$('#p'+(playerId+1)+'name').css({"color":"white"});
	if (prevId == null){
		prevId = playerId;
	}else {
		$('#p'+(prevId+1)+'name').css({"color":"#acacac"});
		prevId = playerId;
	}
	if ($("#activePlayerGlow").length == 0){ // lisame aktiivsele mängijale glow
		$('.pos:eq('+playerId+')').append("<img src='./img/player_frame_glow.png' id = 'activePlayerGlow' style='position:absolute; top: 0px; left: 0px;'/>");
	}
	else {
		$('#activePlayerGlow').appendTo($('.pos:eq('+playerId+')'));
	}
	//$('#totalpot').text("Total pot: " + game.pot+"€");
}
function updatePlayers(players){
	for ( var i = 0; i < players.length; i++) {
		updatePlayerDetails(players[i]);
	}
}

function updatePot(size){
	$('#totalpot').text("Total pot: " + size+"€");
}

function updatePlayerDetails(player){ //TODO: playerId peale teha
	$('#p'+(player.id+1)+'money').text(player.money+"€");
	$('#p'+(player.id+1)+'name').text(player.name);
	var clearQueue = true;
	var gotoEnd = true;
	switch(player.action){
	case(FOLD):
		$('#p'+(player.id+1)+'action').stop(clearQueue, gotoEnd);
		$('#p'+(player.id+1)+'action').text("FOLD").fadeIn(100).delay(3000).fadeOut();
	break;
	case(CHECK):
		$('#p'+(player.id+1)+'action').stop(clearQueue, gotoEnd);
		$('#p'+(player.id+1)+'action').text("CHECK").fadeIn(100).delay(3000).fadeOut();
	break;
	case(CALL):
		$('#p'+(player.id+1)+'action').stop(clearQueue, gotoEnd);
		$('#p'+(player.id+1)+'action').text("CALL").fadeIn(100).delay(3000).fadeOut();
	break;
	case(RAISE):
		$('#p'+(player.id+1)+'action').stop(clearQueue, gotoEnd);
		$('#p'+(player.id+1)+'action').text("RAISE").fadeIn(100).delay(3000).fadeOut();
	break;
	case(ALLIN):
		$('#p'+(player.id+1)+'action').stop(clearQueue, gotoEnd);
		$('#p'+(player.id+1)+'action').text("ALL IN").fadeIn(100).delay(10000).fadeOut();
	break;
	case(WINNER):
		$('#p'+(player.id+1)+'action').stop(clearQueue, gotoEnd);
		$('#p'+(player.id+1)+'action').text("WIN").fadeIn(100).delay(5000).fadeOut();
	break;
	default:
		$('#p'+(player.id+1)+'action').text("");
	}
	
}

function moveDealerButton(player_id){
	$("#dealer").animate({left:playerPosX[player_id],top:playerPosY[player_id]},"slow");
}

var xCoord;
var yCoord;
var playerPosX = [130,200,450,530,530,440,277,235,150]; //mängijate X koordinaatide järjend
var playerPosY = [130,90,90,130,200,280,290,285,200]; //mängijate Y koordinaatide järjend

function animateDealingOfCards(i,cycle,players){
	var speed = 100;
	if (i < players.length) {
		$('#cardanimation').css({
			"position": "absolute",
			"left": "320px",
			"top": "50px",
			"visibility": "visible"
		});
		$('#cardanimation').animate({
			left: playerPosX[players[i].id],
			top: playerPosY[players[i].id]
		}, speed, function(){
			addPlayerCard(players[i],cycle); // lisame kaardi
			animateDealingOfCards(i+1,cycle, players); //kui üks kaart jagatud, jagame järgmise
		});
	}
	if (i==players.length){
		cycle++; 
		if (cycle <= 2) {
			animateDealingOfCards(0, cycle,players); // kui esimene ring kaarte on ära jagatud, siis jagame teise ringi ka
		}
		else {
			$('#cardanimation').css({"left":"320px", "top":"50px", "visibility":"hidden"});
		}
	}
}
function hideCCards(){
	$('.ccard').fadeOut();
}

function animateDealingOfCCards(cCards){
	if (cCards.length > 2){
		animateDealingOfFlop(cCards);
		if (cCards.length > 3){
			animateDealingOfTurn(cCards);
			if (cCards.length == 5){
				animateDealingOfRiver(cCards);
			}
		}
	}
	
}

function animateDealingOfFlop(cCards){
	$('#flop1').css({"background-image": "url(" +cCards[0].image + ")"}).fadeIn();
	$('#flop2').css({"background-image": "url(" +cCards[1].image + ")"}).fadeIn();
	$('#flop3').css({"background-image": "url(" +cCards[2].image + ")"}).fadeIn();
}

function animateDealingOfTurn(cCards){
	$('#turn').css({"background-image": "url(" +cCards[3].image + ")"}).fadeIn();
}

function animateDealingOfRiver(cCards){
	$('#river').css({"background-image": "url(" +cCards[4].image + ")"}).fadeIn();
}

function addPlayerBets(players, bets){
	for ( var i = 0; i < players.length; i++) {
		addPlayerBet(players[i], bets[players[i].id]);
	}
}

function addPlayerBet(player, bet){
	$('#p'+(player.id+1)+'bet').css({"display":"block"});
	$('#p'+(player.id+1)+'bet').text(bet+"€");
}

function removePlayerBet(playerId){
	$('#p'+(playerId+1)+'bet').css({"display":"none"});
}

function removeAllBets(){
	for ( var int = 0; int < 9; int++) {
		$('#p'+(int+1)+'bet').css({"display":"none"});
	}
}
function showPlayerHands(players){
	for ( var i = 0; i < players.length; i++) {
		showPlayerHand(players[i]);
	}
}
function showPlayerHand(player){
	$("#p" + (player.id + 1) + "card1").attr("src",player.hand.cards[0].image);
	$("#p" + (player.id + 1) + "card2").attr("src",player.hand.cards[1].image);
	var delay = SHOWDOWLENGTH-500;
	$("#p" + (player.id + 1) + "card2").animate({
		top: -72, left: 58
	}, "slow").delay(delay).animate({
		"top": -38, "left": 45
	}, "fast");
	
	$("#p" + (player.id + 1) + "card1").animate({
		top: -72, left: 10
	}, "slow").delay(delay).animate({
		top: -38, left: 25
	}, "fast");



}

function showPlayerCards(players){
	for ( var i = 1; i < 3; i++) {
		for ( var j = 0; j < players.length; j++) {
			addPlayerCard(players[j],i);
		}
	}
}
//kaartide jagamise kuvamine vastavalt playerId'le
function addPlayerCard(player,cardNr){
	if (cardNr == 1) {
		if ($("#p" + (player.id + 1)+"card1").length == 0) {
			if (player.isHuman){
				$('.pos:eq(' + player.id + ')').append("<img src='"+ player.hand.cards[0].image + "' class = 'card' id = p" + (player.id + 1) + "card1 style='position:absolute; left:25px; top:-38px;z-index:-1'/>");
			}
			else  //elementi pole veel loodud
				$('.pos:eq(' + player.id + ')').append("<img src='./img/card_back.png' class = 'cardback' id = p" + (player.id + 1) + "card1 style='position:absolute; left:25px; top:-38px;z-index:-1'/>");
		}
		else {
			if (player.isHuman){
				$("#p" + (player.id + 1) + "card1").attr("src",player.hand.cards[0].image);
			}
			else {
				$("#p" + (player.id + 1) + "card1").attr("src","./img/card_back.png");
			}
			$("#p" + (player.id + 1) + "card1").css({"display":"block"});
		}
	}
	else {
		if ($("#p" + (player.id + 1) + "card2").length == 0) {
			if (player.isHuman){
				$('.pos:eq(' + player.id + ')').append("<img src='"+ player.hand.cards[1].image + "' class = 'card' id = p" + (player.id + 1) + "card2 style='position:absolute; left:45px; top:-38px;z-index:-1'/>");
			}
			else 
				$('.pos:eq(' + player.id + ')').append("<img src='./img/card_back.png' class = 'cardback' id = p" + (player.id + 1) + "card2 style='position:absolute; left:45px; top:-38px;z-index:-1'/>");
		}
		else {
			if (player.isHuman){
				$("#p" + (player.id + 1) + "card2").attr("src",player.hand.cards[1].image);
			}
			else {
				$("#p" + (player.id + 1) + "card2").attr("src","./img/card_back.png");
			}
			$("#p" + (player.id + 1) + "card2").css({"display":"block"});
		}
	}
}

function hidePlayersCards(players){
	for ( var i = 0; i < 9; i++) {
		hidePlayerCards(i);
	}
}

function hidePlayerCards(playerId){
	$("#p" + (playerId + 1) + "card1").fadeOut();
	$("#p" + (playerId + 1) + "card2").fadeOut();
}

function getTextFromTextinput(){
	var input =  $("#textinput").val();
	if (input != ""){
		$("#textinput").val("");
		sendToChat("You", input);
		sendMessage("You: " + input);
	}
}

function sendToChat(name,text){
	var chatText = $("#chattextarea").val();
	if (chatText == ""){
		chatText += name+": " + text;
	}
	else {
		chatText += "\r\n"+name+": " + text;
	}
	$("#chattextarea").val(chatText);
	$("#chattextarea").animate({ scrollTop: $("#chattextarea")[0].scrollHeight }, 1000);
}

function changeCheckToCallButton(){
	$("#checkbutton").val("Call");
}

function changeCallToCheckButton(){
	$("#checkbutton").val("Check");
}
function changeCallToAllInButton(){
	$("#checkbutton").val("All in");
}

function changeRaiseToAllInButton(){
	$("#raisebutton").val("All in");
}

function restoreRaiseButton(){
	$("#raisebutton").val("Raise");
}
function startLeave(){
	if ($("#startleavebutton").val() != "Leave")
	{
		isGameRunning();
		//startGame();
		
	}
	else
	{
		if (endGame()){
			endGameInServer();
			UPDATING = false;
			showPlayerButtons(false);
			cleanTable();
			hideCCards();
			$("#startleavebutton").val("Start");
		}
	}	
}

function startGame(isGameRunning){
	if (isGameRunning == true){
		var answer  = confirm("Leiti pooleliolev mäng, soovid ühenduda?");
		if (answer){
			sendAction("restore");
		}
		else {
			sendAction("start");
		}
	}
	else {
		sendAction("start");
	}
	update();
	$("#startleavebutton").val("Leave");
}

function cleanTable(){
	for ( var i = 0; i < 9; i++) {
		hidePlayerCards(i);
		removePlayerBet(i);
	}
}
function endGame(){
	$(".main").attr('id', 'overlay');
	var answer  = confirm("Oled kindel, et tahad mängust lahkuda?");
	$(".main").attr('id', '');
	return answer;
}

function gameOver(){
	showPlayerButtons(false);
	cleanTable();
	hideCCards();
	$("#startleavebutton").val("Start");
}


function disableRaiseButton(){
	$("#raisebutton").attr('disabled', true);
	$("#raisebutton").css({"background-image":"url(./img/button_inactive.png)"});
}

function enableRaiseButton(){
	$("#raisebutton").attr('disabled', false);
	$("#raisebutton").css({"background-image":"url(./img/button_blue.png)"});
}

function stopFor(millis)
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); }
	while(curDate-date < millis);
} 